let enabled = true;

const getExtName = url => {
	let i, n = url.indexOf('?', 21);
	if (-1 != n) i = n-3;
	else {
		i = url.length - 4;
		n = void 0;
	}
	i = url.lastIndexOf('.',i) +1;
	if (i) return url.slice(i, n);
};
const getFileName = url => {
	let i, n = url.indexOf('?',33);
	if (-1 != n) i = n-3;
	else {
		i = url.length - 4;
		n = void 0;
	}
	i = url.lastIndexOf('.',i) +1;
	if (!i) return;
	i = url.lastIndexOf('/',i-3) +1;
	return {pos: i, fname: url.slice(i, n)};
};
const toByteUnit = bytes => {
	if (bytes < 1024) return bytes +'';
	const symbols = Array.from('BKMGTPEZYB');
	const exp = ~~(Math.log(bytes)/Math.log(2));
	const i = ~~(exp / 10);
	bytes /= 2 ** (10 * i);
	bytes = bytes.toFixed(2).replace(/\.?0+$/,'');
	return bytes.slice(0,3) + symbols[i];
};
const allMVs = new Map();
const saveMV = (tabId, detail) => {
	let text = '1', a = allMVs.get(tabId);
	if (!a) allMVs.set(tabId, Array.of(detail));
	else if (a.some(k => k.url == detail.url)) return;
	else text = toByteUnit(a.unshift(detail));
	chrome.browserAction.setBadgeText({tabId, text});
};

const libManager = {
	loadedTab: new Map(),
	_vLib: { normal:1,hls:2,dash:4,flv:8,auto:-1 },
	initOnTab(tabId) {
		this.loadedTab.delete(tabId);
	},
	isLoaded(tabId) {
		return this.loadedTab.has(tabId);
	},
	getVideoType(url) {
		const ext = getExtName(url);
		if (/mp4|ogg|webm/.test(ext)) return 1;
		if (ext == 'm3u8') return 2;
		if (ext == 'mpd') return 4;
		if (ext == 'flv') return 8;
		if (url.includes('/hls/', 11) || url.includes('m3u8', 7)) return 2;
		if (url.includes('.mpd', 25)) return 4;
		// else 此情形加载所有库
		return 1;
	},
	inject(tabId, url, type = -1) {
		if (!enabled) return;
		if (typeof type == 'string') type = this._vLib[type] || -1;
		const loadedType = this.loadedTab.get(tabId) || 0;
		if (loadedType && (loadedType & 15) == 15) return;

		if (type == -1) type = this.getVideoType(url);
		if (type != 1) saveMV(tabId, {url, kind: type});
		type |= 1;

		if ((type & 2) && !(loadedType & 2))
			chrome.tabs.executeScript(tabId,{file:"lib/hls.min.js"});
		else if ((type & 4) && !(loadedType & 4))
			chrome.tabs.executeScript(tabId,{file:"lib/dash.all.min.js"});
		else if ((type & 8) && !(loadedType & 8))
			chrome.tabs.executeScript(tabId,{file:"lib/flv.min.js"});
		if (!(loadedType & 1)) {
			chrome.tabs.insertCSS(tabId,{file:"player-fix.css"});
			chrome.tabs.executeScript(tabId,{file:"lib/DPlayer.min.js"});
		}
		this.loadedTab.set(tabId, loadedType | type);
	}
};